import 'package:flutter/foundation.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/inspiration/catgory_list.dart';
import 'package:loxen/mode/material/material_item.dart';
import 'package:loxen/mode/material/material_list_bean.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';

class ItemEntity {
  MaterialItem materialItem1;
  MaterialItem materialItem2;
}

class MaterialCategoryViewModel extends BaseViewModel {
  BaseMode<CategoryList> _categoryBean;

  BaseMode<CategoryList> get categoryBean => _categoryBean;

  int currentCategory = 0;
  int currentCategoryId = 0;
  int oldCategoryId = 0;

  final Map<String, List<List<ItemEntity>>> _map = {};

  final int pageSize = 4;
  PagewiseLoadController<ItemEntity> controller;

  MaterialCategoryViewModel() {
    controller = PagewiseLoadController<ItemEntity>(pageSize: pageSize, pageFuture: nextData);
  }

  //刷新列表内容
  void refresh() {
    String key = _categoryBean.data.results[currentCategory].sub_category[currentCategoryId].id;
    if (_map.containsKey(key)) {
      _map[key].clear();
    }
    controller.reset();
  }

  //一级分类切换
  void changeCategory(int index) {
    currentCategory = index;
    changeCategoryId(0);
    notifyListeners();
  }

  //二级分类切换
  void changeCategoryId(int index) {
    oldCategoryId = currentCategoryId;
    currentCategoryId = index;
    controller.reset();
    notifyListeners();
  }

  //下一页数据
  Future<List<ItemEntity>> nextData(int page) async {
    String key = _categoryBean.data.results[currentCategory].sub_category[currentCategoryId].id;
    if (_map.containsKey(key)) {
      if (_map[key].length - 1 >= page) {
        return _map[key][page];
      } else {
        var data = await ApiService.materialProduct(category: key, page: (page + 1).toString())
            .flatMap((value) => compute(decodeMaterialListBean, value.data).asStream())
            .first;
        List<ItemEntity> list = [];
        for(int i = 0;i < data.data.results.length ; i+=2) {
          ItemEntity entity = ItemEntity();
          entity.materialItem1 = data.data.results[i];
          if(i+1 < data.data.results.length) {
            entity.materialItem2 = data.data.results[i+1];
          }
          list.add(entity);
        }
        _map[key].add(list);
        return list;
      }
    } else {
      var data = await ApiService.materialProduct(category: key, page: (page + 1).toString())
          .flatMap((value) => compute(decodeMaterialListBean, value.data).asStream())
          .first;
      List<ItemEntity> list = [];
      for(int i = 0;i < data.data.results.length ; i+=2) {
        ItemEntity entity = ItemEntity();
        entity.materialItem1 = data.data.results[i];
        if(i+1 < data.data.results.length) {
          entity.materialItem2 = data.data.results[i+1];
        }
        list.add(entity);
      }
      _map.putIfAbsent(key, () => <List<ItemEntity>>[list]);
      return list;
    }
  }

  //加载数据
  void loadData(String category) {
    if (mState == BaseState.LOADING) return;
    ApiService.materialCategory()
        .doOnListen(() => mState = BaseState.LOADING)
        .flatMap((value) => compute(decodeCategoryBean, value.data).asStream())
        .flatMap((value) {
          _categoryBean = value;
          var categories = value.data.results;
          var id;
          for (int i = 0; i < categories.length; i++) {
            if (categories[i].name == category) {
              id = categories[i].sub_category[0].id;
              currentCategory = i;
              break;
            }
          }
          return ApiService.materialProduct(category: id);
        })
        .flatMap((value) => compute(decodeMaterialListBean, value.data).asStream())
        .listen((data) {
          if (data.data.count > 0) {
            mState = BaseState.CONTENT;
            String key =
                _categoryBean.data.results[currentCategory].sub_category[currentCategoryId].id;
            List<ItemEntity> list = [];
            for(int i = 0;i < data.data.results.length ; i+=2) {
              ItemEntity entity = ItemEntity();
              entity.materialItem1 = data.data.results[i];
              if(i+1 < data.data.results.length) {
                entity.materialItem2 = data.data.results[i+1];
              }
              list.add(entity);
            }
            _map.putIfAbsent(key, () => <List<ItemEntity>>[list]);
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error, stackTrace) {
          mState = BaseState.FAIL;
          print(error);
          print(stackTrace);
        }, onDone: () => notifyListeners());
  }

  static MaterialListBean decodeMaterialListBean(dynamic json) {
    return MaterialListBean.fromJson(json);
  }

  static BaseMode<CategoryList> decodeCategoryBean(dynamic json) {
    return BaseMode<CategoryList>(json);
  }
}
